package com.controller;

import com.entity.Login;
import com.entity.LoginResBody;
import com.entity.LoginUser;
import com.entity.TokenList;
import com.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.swing.plaf.basic.BasicScrollPaneUI;
import java.util.*;

/**
 * @author WZ
 * @version 1.0
 * @date 2021/8/23 10:00
 */
@Controller
public class LoginController {
    @Autowired
private LoginService loginService;
//用来控制token时效

    public  static List<TokenList> tokenLists=new ArrayList<TokenList>();


    class TimeOutTask extends TimerTask {

        @Override
        public void run() {
           if (!tokenLists.isEmpty()){
               tokenLists.remove(0);
           }
        }
    }



    public static Boolean existToken(String token) {
        boolean hass=false;
        for (int i = 0; i < tokenLists.size(); i++) {
          if (tokenLists.get(i).getToken().equals(token)){
             hass=true;
          }
        }
        return hass;
    }

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    @CrossOrigin
    public LoginResBody login(@RequestBody Login login) {


        List<Login> lllogin = loginService.login(login.getAccount());
        if (!lllogin.isEmpty()) {
            if (lllogin.get(0).getPassword().equals(login.getPassword())) {

                boolean hasToken = false;
                String tokenForHas="";
                List<LoginUser> userData = loginService.finduserlist(login.getAccount());
                for (int i = 0; i < tokenLists.size(); i++) {
                    if (tokenLists.get(i).getUserId().equals(userData.get(0).getUserId())) {
                        hasToken = true;
                        tokenForHas=tokenLists.get(i).getToken();
                    }
                }
                if (hasToken == false) {
                    String accessToken1 = UUID.randomUUID().toString().replaceAll("-", "");
                    TokenList token1 = new TokenList(accessToken1, "on", userData.get(0).getUserId());
                    tokenLists.add(token1);
                    String accessToken2 = token1.getToken();

                    Timer timer = new Timer();
                    TimeOutTask tot = new TimeOutTask();
                    timer.schedule(tot, 1000*60*60*24);
                    return new LoginResBody("200", "成功", accessToken2, userData);
                }else {
                    return new LoginResBody("200", "成功", tokenForHas, userData);
                }


            } else {

                return new LoginResBody("500", "帐号或密码不正确");
            }
        }
        else {
            return new LoginResBody("500", "帐号或密码不正确");
        }


    }


}
